package gk.cxd.friday.config;


import gk.cxd.friday.common.security.filter.JwtAuthenticationTokenFilter;
import gk.cxd.friday.common.security.handle.AuthenticationEntryPointImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;


/**
 *配置Spring Security
 */
@EnableGlobalMethodSecurity(prePostEnabled = true,securedEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter /*继承适配器*/{
    /**
     * 自定义用户认证逻辑
     */
    @Autowired
    private UserDetailsService userDetailsService;
    //认证失败的处理
    @Autowired
    private AuthenticationEntryPointImpl unanthorizeHandler;
    /**
     * token的认证过滤器
     */
    @Autowired
    private JwtAuthenticationTokenFilter authenticationTokenFilter;
    /**
     *强散列哈希加密实现
     */
    @Bean
    public BCryptPasswordEncoder bCryptPasswordEncoder(){
        return new BCryptPasswordEncoder();
    }

    /**
     *身份认证接口
     * @param auth
     * @throws Exception
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(bCryptPasswordEncoder());
    }

    /**
     * 解决无法直接注入AuthenticationManager
     */
    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }
    /**
     * 设置访问规则
     * @param httpSecurity
     * @throws Exception
     */
    @Override
    protected void configure(HttpSecurity httpSecurity) throws Exception {
        //添加JWT过滤器
        httpSecurity.addFilterBefore(authenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);
        httpSecurity
                //禁用session
                .csrf().disable()
                //认证失败的处理
                .exceptionHandling().authenticationEntryPoint(unanthorizeHandler)
                .and()
                //设置token
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
                //设置过滤器，过滤请求
                .authorizeRequests()
                //设置登录规则
                .antMatchers("/login", "/profile/avatar/**").anonymous() //表示可以匿名请求
                .antMatchers(
                        HttpMethod.GET,
                        "/*.html",
                        "/**/*.html",
                        "/**/*.css",
                        "/**/*.js"
                ).permitAll() //设置不阻止静态资源
                .antMatchers("/profile/**").anonymous()
                //除去以上内容，其他的请求都需要认证（登录）
                .anyRequest().authenticated()
                .and()
                .headers().frameOptions().disable();
    }
}
